import {Select, Space} from 'antd'
import styled from './index.module.scss'
import {useEffect, useState, CSSProperties} from 'react'
import {codeAddress} from '@/api'
import {addressList} from '@/type/componentType'


type options = {
	label: string,
	value: number
}
export const Address = (props:{
	value: string
	onChange: (value: string) => void
	style: CSSProperties
}) => {
	console.log(props)
	// 区
	const [city, setCity] = useState<options[]>([])
	// 市
	const [area, setArea] = useState<options[]>([])
	// 省
	const [province, setProvince] = useState<options[]>([])

	const [value, setValue] = useState<{
		city: number | null
		area: number | null
		province: number | null
	}>({
		city: null,
		area: null,
		province: null
	})

	useEffect(() => {
		if (props.value) {
			const list = props.value.split("-")
			codeAddress().then(res => {
				if (res.code === 200) {
					codeAddress({id: list[0] as number}).then(res1 => {
						if (res1.code === 200) {
							codeAddress({id: list[1] as number}).then(res2 => {
								if (res2.code === 200) {
									setProvince(res.data)
									setArea(res1.data)
									setCity(res2.data)
								}
							})
						}
					})
				}
			})
		}else {
			getList(setProvince)
		}
	}, [props.value])

	useEffect(() => {
		if (value.city) {
			props.onChange(`${value.province}-${value.area}-${value.city}`)
		}
	}, [value.city])

	function getList (set, data?:{id: number| null}, ) {
		codeAddress(data).then(res => {
			if (res.code === 200) {
				set(res.data)
			}
		})
	}

	const provinceChange = (v: number) => {
		setValue((x) => ({
			...x,
			province: v
		}))
		getList(setArea, {id: v})
	}

	const areaChange = (v: number) => {
		setValue((x) => ({
			...x,
			area: v
		}))
		getList(setCity, {id: v})
	}

	const cityChange = (v: number) => {
		setValue((x) => ({
			...x,
			city: v
		}))
	}





	return (
		<div className={styled.space}>
			<Space style={props.style} >
				<Select value={value.province} onChange={provinceChange} options={province} style={{width: '100%'}}></Select>
				<Select value={value.area} onChange={areaChange} options={area} style={{width: '100%'}}></Select>
				<Select value={value.city} onChange={cityChange} options={city} style={{width: '100%'}}></Select>
			</Space>
		</div>
	)
}
